/*
 * BSM6.0
 *
 * Copyright 2012-2013 (C) SINODATA CO., LTD. All Rights Reserved.
 */
package com.sinodata.bsm.center.service.probe;

import java.util.*;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.sinodata.bsm.center.cache.ProbeCache;
import com.sinodata.bsm.center.dao.BaseDao;
import com.sinodata.bsm.center.engine.probe.ProbeStatusManager;
import com.sinodata.bsm.center.message.PropertyValueListener;
import com.sinodata.bsm.common.constants.SystemStatus;
import com.sinodata.bsm.common.vo.Probe;

/**
 * <p>
 * Description: 
 * </p>
 *
 * @author tangli
 * @version 1.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * 2012-5-14 下午5:16:24          tangli         1.0         To create
 * </p>
 *
 * @since 
 * @see     
 */
@Service
@Transactional(propagation = Propagation.NOT_SUPPORTED)
public class ProbeStatusService {
    private static final Logger logger = Logger.getLogger(ProbeStatusService.class);
    @Autowired
    private BaseDao baseDao;
    @Autowired
    private ProbeCache probeCache;

    /**
     * 
     */
    public ProbeStatusService() {
    }

    /**
     * Probe注册工作
     * 更新Probe的信息（DB和Cache），如果没有信息则新增
     * 启动指标的队列的监听
     * @param probeId
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public String registry(Long probeId, String probeName, String probeType, String ip) {
        logger.info("Probe Registry:id=" + probeId + ",name=" + probeName + ",type=" + probeType);
        Probe probe = (Probe) baseDao.findById(Probe.class, probeId);
        if (probe == null) {
            probe = new Probe();
            probe.setId(probeId);
            probe.setCreateDate(new Date());
        }
        probe.setName(probeName);
        probe.setType(probeType);
        probe.setIp(ip);
        probe.setDesc(probeId + "@" + ip + "@" + probeName);
        probe.setStatus(SystemStatus.STATUS_INIT);
        baseDao.saveOrUpdate(probe);
        probeCache.put(probeId, probe);
        return "";
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public String finishStartup(Long probeId) {
        Probe probe = probeCache.get(probeId);
        if (probe == null) {
            return "Probe不存在";
        }
        probe.setStartDate(new Date());
        probe.setStatus(SystemStatus.STATUS_RUN);
        baseDao.saveOrUpdate(probe);
        PropertyValueListener.newInstance(probeId);
        return "";
    }
}
